﻿Imports OMANE.Common.UI
Imports System.Windows.Input
Imports System.IO
Imports System.Runtime.Serialization.Formatters.Binary
Imports System.Runtime.Serialization
Imports Actuariat
Imports OMANE.Common.Model.Parametrage
Imports Microsoft.Practices.Prism.Commands

Namespace ViewModels
    Public Class ViewModelMethodeDeCalcul
        Inherits ViewModelCommand
        Implements IViewModelTabSection

        Private _model As ModelTauxGarantis
        Public Property IsClosable As Boolean Implements IViewModelTabSection.IsClosable

        Public Sub New(ByVal Model As ModelTauxGarantis, ByVal DisplayName As String, ByVal Command As ICommand)
            MyBase.New(DisplayName, Command)
            _model = Model
            SegmentProvider.model = Model
            Title = "METHODE DE CALCUL"
        End Sub

        Public Property Icone As String Implements Common.UI.IViewModelTabSection.Icone
        Public Property Title As String Implements Common.UI.IViewModelTabSection.Title

        Sub New()
        End Sub

        Public Property IsEquilibreTarifaire As Boolean
            Get
                Return (_model.numMethodeCalculEnCours = 1)
            End Get
            Set(ByVal value As Boolean)
                _model.numMethodeCalculEnCours = If(value, 1, 2)
                OnPropertyChanged("IsEquilibreTarifaire")
                OnPropertyChanged("IsProjectionDesCompte")
            End Set
        End Property
        Public Property IsProjectionDesCompte As Boolean
            Get
                Return (_model.numMethodeCalculEnCours = 2)
            End Get
            Set(ByVal value As Boolean)
                _model.numMethodeCalculEnCours = If(value, 2, 1)
                OnPropertyChanged("IsProjectionDesCompte")
                OnPropertyChanged("IsEquilibreTarifaire")
            End Set
        End Property

        Public ReadOnly Property LoadParametres As ICommand
            Get
                Return New DelegateCommand(Of Object)(AddressOf LoadParametresExecute, AddressOf LoadParametresCanExecute)
            End Get
        End Property
        Private Function LoadParametresCanExecute(ByVal parameter As Object) As Boolean
            'Vérifier que la base d'encours est entièrement qualifiée
            Return True
        End Function
        Private Sub LoadParametresExecute(ByVal parametre As Object)
            'Chargement des correspondances sauvegardées
            'baseListeChampsSortieTable.load(openFileDialog1.FileName, _model.Univers.listeTraitements.TraitTbleEncours)

            'Ouvrir une boite de dialogue
            Dim dlg As New Microsoft.Win32.OpenFileDialog
            dlg.InitialDirectory = PTIC_Util.csteEmplacementParametrage
            dlg.DefaultExt = ".omp"
            dlg.Filter = "Paramètres Techniques (.omp)|*.omp"
            Dim old = System.Windows.Input.Mouse.OverrideCursor

            If dlg.ShowDialog Then
                Try

                    System.Windows.Input.Mouse.OverrideCursor = System.Windows.Input.Cursors.AppStarting

                    Dim filename As String = dlg.FileName
                    Dim lParametres As IDictionary(Of String, IParametre) = Nothing
                    'Récupération du contenu du fichier dans un objet Mapping
                    Dim myFileStream As Stream = File.OpenRead(filename)
                    Dim deserializer As New BinaryFormatter()
                    lParametres = CType(deserializer.Deserialize(myFileStream), IDictionary(Of String, IParametre))
                    myFileStream.Close()

                    'Mettre à jour la segmentation en fonction des paramètres ayant été chargés
                    Dim modifSeg As Boolean = False
                    For Each param As IParametre In lParametres.Values
                        For Each seg As String In param.ListeSegments
                            If Not _model.Segmentation.Retenue.ContainsKey(seg) Then
                                Dim lSegAAjouter As New List(Of PTIC_GestionBDD.Correspondance)
                                lSegAAjouter.Add(_model.ListeTraitements.TraitTbleEncoursPrep1.ListeChampsSortie(seg))
                                _model.Segmentation.modifSegRetenue(lSegAAjouter, PTIC_GestionBDD.operationCollection.ADD)
                                _model.Segmentation.modifSegPossibleNonRetenue(lSegAAjouter, PTIC_GestionBDD.operationCollection.REMOVE)
                                modifSeg = True
                            End If
                        Next
                    Next
                    If modifSeg Then _model.ListeTraitements.TraitReqSegmentation.Calculer_DataTable()

                    'Parcourir tous les paramètres et charger les valeurs
                    For Each param As IParametre In lParametres.Values
                        _model.ListeParametres.Item(param.Nom).Deserialize(param)
                    Next

                    System.Windows.Input.Mouse.OverrideCursor = old

                Catch ex As Exception
                    System.Windows.Input.Mouse.OverrideCursor = old
                End Try
            End If
        End Sub

        Public ReadOnly Property SaveParametres As ICommand
            Get
                Return New DelegateCommand(Of Object)(AddressOf SaveParametresExecute, AddressOf SaveParametresCanExecute)
            End Get
        End Property
        Private Function SaveParametresCanExecute(ByVal parameter As Object) As Boolean
            Return True
        End Function
        Private Sub SaveParametresExecute(ByVal parametre As Object)
            Dim dlg As New Microsoft.Win32.SaveFileDialog
            dlg.InitialDirectory = PTIC_Util.csteEmplacementParametrage
            dlg.DefaultExt = ".omp"
            dlg.Filter = "Paramètres Techniques (.omp)|*.omp"

            Dim old = System.Windows.Input.Mouse.OverrideCursor

            If dlg.ShowDialog Then

                System.Windows.Input.Mouse.OverrideCursor = System.Windows.Input.Cursors.AppStarting

                Dim filename As String = dlg.FileName

                'Sauvegarde de la liste de champs
                Dim myFileStream As IO.Stream = IO.File.Create(filename, FileMode.Create)
                Dim serializer As New BinaryFormatter
                Try
                    Dim lSerializedParametres As IDictionary(Of String, IParametre) = New Dictionary(Of String, IParametre)
                    For Each param As KeyValuePair(Of String, IParametre) In _model.ListeParametres
                        lSerializedParametres.Add(param.Key, param.Value)
                    Next
                    serializer.Serialize(myFileStream, lSerializedParametres)
                Catch e As SerializationException
                    System.Windows.Input.Mouse.OverrideCursor = old
                    MsgBox("Echec de la serialization. Cause : " & e.Message)
                Finally
                    System.Windows.Input.Mouse.OverrideCursor = old
                    myFileStream.Close()
                End Try

            End If
        End Sub

        Public ReadOnly Property InitialisationCommand As ICommand
            Get
                Return New DelegateCommand(Of Object)(AddressOf ExecuteInitialisation, AddressOf CanExecuteInitialisation)
            End Get
        End Property
        Private Sub ExecuteInitialisation(ByVal parameter As Object)

        End Sub
        Private Function CanExecuteInitialisation(ByVal parameter As Object) As Boolean
            Return True
        End Function
    End Class
End Namespace
